package com.car.carsharing.controller;

import com.car.carsharing.dto.LoginDTO;
import com.car.carsharing.dto.ResponseDTO;
import com.car.carsharing.pojo.User;
import com.car.carsharing.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "login",method = RequestMethod.POST)
    public ResponseDTO login(@RequestBody LoginDTO dto){
        if(dto == null ||dto.getUsername() == null || "".equals(dto.getUsername()) || dto.getPassword() == null || "".equals(dto.getPassword())){
            return new ResponseDTO().error("用户名或密码为空");
        }
        User user = userService.login(dto.getUsername(),dto.getPassword());
        if(user == null ){
            return new ResponseDTO().error("密码或账号错误");
        }
        return new ResponseDTO().success(user.getId(),"登录成功");
    }

    @RequestMapping("regist")
    public ResponseDTO regist(String username,String password){
        if(username == null || "".equals(username) || password == null || "".equals(password)){
            return new ResponseDTO().error("用户名或密码为空");
        }

        Integer userId = userService.regist(username,password);
        if(userId == -1){
            return new ResponseDTO().error("账号已存在");
        }
        return new ResponseDTO().success(userId,"注册成功");
    }
}
